#!/bin/bash
# ======================================================================
# Script: update-code-server-proxy-url.sh
# Author: lijun <szulijun@qq.com>
# Date: 2025-05-23
# Description: 更新readme.md中code-server代理url。
# Usage: ./update-code-server-proxy-url.sh
# Use case: 在.cnb.yml配置运行。
# ====================================================================== 
set -ex

if [ -z "$VSCODE_PROXY_URI" ]; then
    echo "VSCODE_PROXY_URI is null"
    if [ -z "$CNB_VSCODE_PROXY_URI" ]; then
        echo "CNB_VSCODE_PROXY_URI is null"
        exit 0
    fi
fi    
    

# 定义文件路径
README_FILE="/workspace/README.md"
# 获取旧容器ID内容
OLD_PART=$(grep -o "[a-zA-Z0-9]*-18686\.cnb\.run" "$README_FILE" | head -1 | sed 's/-18686\.cnb\.run//' | sed 's/https:\/\///')
echo "old id：$OLD_PART"

# 获取新内容
NEW_PART=$(echo $CNB_VSCODE_PROXY_URI | sed 's/https:\/\///' | sed 's/-{{port}}.cnb.run//')
echo "new id:$NEW_PART"

# 执行替换
if [ -n "$OLD_PART" ]; then
    sed -i "s/$OLD_PART/$NEW_PART/g" "$README_FILE"
    echo "已将 $OLD_PART 替换为 $NEW_PART"
else
    echo "未找到要替换的内容"
fi

# 推送到仓库
/bin/push-all-file-to-git